
import moment from 'moment';
import { Rule } from 'rc-field-form/lib/interface';
import { formatFileList } from '~/components/PictureUploader';

const getUrlSearch = (name: string) => {
  if (!name) return null;
  let after = window.location.search;
  after = after.substr(1) || window.location.hash.split('?')[1];
  if (!after) return null;
  if (!after.includes(name)) return null;
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
  // eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
  const r = decodeURI(after).match(reg);
  if (!r) return null;
  return r[2];
};

const genValidConfig = (params: any) => {
  const config: Rule = {
    required: params.required !== 'false',
    type: params.type || 'string',
  };

  // numString
  if (params.selfType === 'numString') {
    const validator = (_: Rule, value: string) => {
      if (!value && !config.required) return Promise.resolve(); // 不是必填项，不需校验
      if (isNaN(Number(value))) {
        return Promise.reject(new Error('Not a validate number'));
      }
      return Promise.resolve();
    };
    config.validator = validator;
  }

  // phone
  if (params.selfType === 'phone') {
    const validator = (_: Rule, value: string) => {
      if (!value && !config.required) return Promise.resolve(); // 不是必填项，不需校验
      if (!/^1[3456789]\d{9}$/.test(value)) {
        return Promise.reject(new Error('Not a validate phone'));
      }
      return Promise.resolve();
    };
    config.validator = validator;
  }

  return [config];
};

// uuid  token
const guid = () => {
  function S4() {
    // eslint-disable-next-line no-bitwise
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return `${S4() + S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
};

// 删除空附件
const deleteNullValue = (data: Array<object>) => {
  const _data = data.filter((item: any) => item.fileUrl);
  return _data;
};

// 阶段1 switch初始值
const getStageOneInitialValue = () => {
  const value = {
    fsrView: true,
    eiaView: true,
    plannedGovernmentSpendingView: true,
    riskAllocationFrameworkView: true,
    contractCoreContentView: true,
    indicatorsAndSystemView: true,
    contractSystemView: true,
    regulatoryFrameworkView: true,
    foreignInvestorsTaxPolicyView: true,
    foreignInvestorsExchangePolicyView: true,
    faaView: true,
    vfmView: true,
  };

  return value;
};

// 基础表单数据--处理
const handleFormValue = (values: any) => {
  const formData: any = {
    ...values,
    plannedYear: parseInt(values.plannedYear, 10),
    governmentAuthDoc: values.governmentAuthDoc ? values.governmentAuthDoc.map((v: any) => v.response.data).toString() : '',
    thumbnail: values.thumbnail ? values.thumbnail.map((v: any) => v.response.data).toString() : '',
  };

  return formData;
};

// 阶段1 表单数据--处理
const handleStageOneValue = (values: any) => {
  const formData: any = {
    ...values,
    fsrView: values.fsrView ? 1 : 0,
    eiaView: values.eiaView ? 1 : 0,
    vfmView: values.vfmView ? 1 : 0,
    faaView: values.faaView ? 1 : 0,
    plannedGovernmentSpendingView: values.plannedGovernmentSpendingView ? 1 : 0,
    riskAllocationFrameworkView: values.riskAllocationFrameworkView ? 1 : 0,
    contractCoreContentView: values.contractCoreContentView ? 1 : 0,
    indicatorsAndSystemView: values.indicatorsAndSystemView ? 1 : 0,
    contractSystemView: values.contractSystemView ? 1 : 0,
    regulatoryFrameworkView: values.regulatoryFrameworkView ? 1 : 0,
    foreignInvestorsTaxPolicyView: values.foreignInvestorsTaxPolicyView ? 1 : 0,
    foreignInvestorsExchangePolicyView: values.foreignInvestorsExchangePolicyView ? 1 : 0,
    totalLandArea: parseInt(values.totalLandArea, 10),
    totalLength: parseInt(values.totalLength, 10),
    plannedTotalInvestment: parseInt(values.plannedTotalInvestment, 10),
    returnMechanism: parseInt(values.returnMechanism, 10),
    projectContractTerm: parseInt(values.projectContractTerm, 10),
    plannedPriInvestmentAmount: parseInt(values.plannedPriInvestmentAmount, 10),
    plannedCompletionDate: new Date(values.plannedCompletionDate).getTime(),
    plannedStartDate: new Date(values.plannedStartDate).getTime(),
    plannedOperationStartDate: new Date(values.plannedOperationStartDate).getTime(),
    plannedProcurementDate: new Date(values.plannedProcurementDate).getTime(),
    fsrApprovalDate: new Date(values.fsrApprovalDate).getTime(),
    eiaApprovalDate: new Date(values.eiaApprovalDate).getTime(),
    fsr: values.fsr ? values.fsr.map((v: any) => v.response.data).toString() : '',
    eia: values.eia ? values.eia.map((v: any) => v.response.data).toString() : '',
    riskAllocationFramework: values.riskAllocationFramework ? values.riskAllocationFramework.map((v: any) => v.response.data).toString() : '',
    contractCoreContent: values.contractCoreContent ? values.contractCoreContent.map((v: any) => v.response.data).toString() : '',
    indicatorsAndSystem: values.indicatorsAndSystem ? values.indicatorsAndSystem.map((v: any) => v.response.data).toString() : '',
    contractSystem: values.contractSystem ? values.contractSystem.map((v: any) => v.response.data).toString() : '',
    regulatoryFramework: values.regulatoryFramework ? values.regulatoryFramework.map((v: any) => v.response.data).toString() : '',
  };

  return formData;
};

// 阶段2 表单数据--处理
const handleStageTwoValue = (values: any) => {
  const formData: any = {
    ...values,
    contractBudgetExpenditure: parseInt(values.contractBudgetExpenditure, 10),
    privateAgreedInvestmentAmount: parseInt(values.privateAgreedInvestmentAmount, 10),
    contractSigningDate: new Date(values.contractSigningDate).getTime(),
    approvalDate: new Date(values.approvalDate).getTime(),
    tenderSubmissionDeadline: new Date(values.tenderSubmissionDeadline).getTime(),
    finalNegotiationDate: new Date(values.finalNegotiationDate).getTime(),
    preQualificationAnnouncement: values.preQualificationAnnouncement ? values.preQualificationAnnouncement.map((v: any) => v.response.data).toString() : '',
    preQualifiedShortlist: values.preQualifiedShortlist ? values.preQualifiedShortlist.map((v: any) => v.response.data).toString() : '',
    rfp: values.rfp ? values.rfp.map((v: any) => v.response.data).toString() : '',
    bidderList: values.bidderList ? values.bidderList.map((v: any) => v.response.data).toString() : '',
    bidsEvaluationResult: values.bidsEvaluationResult ? values.bidsEvaluationResult.map((v: any) => v.response.data).toString() : '',
    theSignedContract: values.theSignedContract ? values.theSignedContract.map((v: any) => v.response.data).toString() : '',
    contractCoreTerms: values.contractCoreTerms ? values.contractCoreTerms.map((v: any) => v.response.data).toString() : '',
  };

  return formData;
};

// 阶段3 表单数据--处理
const handleStageThreeValue = (values: any) => {
  const formData: any = {
    ...values,
    pcRegisteredCapital: parseInt(values.pcRegisteredCapital, 10),
    pcShareholdersPayProjectCapital: parseInt(values.pcShareholdersPayProjectCapital, 10),
    govExpenditureEachYear: parseInt(values.govExpenditureEachYear, 10),
    pcFoundDate: new Date(values.pcFoundDate).getTime(),
    constructionStartDate: new Date(values.constructionStartDate).getTime(),
    constructionCompletionDate: new Date(values.constructionCompletionDate).getTime(),
    operationStartDate: new Date(values.operationStartDate).getTime(),
    performanceAssuranceMeasures: values.performanceAssuranceMeasures ? values.performanceAssuranceMeasures.map((v: any) => v.response.data).toString() : '',
  };

  return formData;
};

// 阶段4 表单数据--处理
const handleStageFourValue = (values: any) => {
  const formData: any = {
    ...values,
    completionTime: new Date(values.completionTime).getTime(),
    warrantyPeriod: parseInt(values.warrantyPeriod, 10),
    transferList: values.transferList ? values.transferList.map((v: any) => v.response.data).toString() : '',
    assessmentReport: values.assessmentReport ? values.assessmentReport.map((v: any) => v.response.data).toString() : '',
    performanceTestPlan: values.performanceTestPlan ? values.performanceTestPlan.map((v: any) => v.response.data).toString() : '',
    testResult: values.testResult ? values.testResult.map((v: any) => v.response.data).toString() : '',
    followUpOperation: values.followUpOperation ? values.followUpOperation.map((v: any) => v.response.data).toString() : '',
  };

  return formData;
};

// 数据回显 -- 格式处理
const echoFormValue = (values: any) => {
  const {
    plannedYear = '',
    governmentAuthDoc,
    thumbnail,
  } = values;
  const formData: any = {
    ...values,
    plannedYear: plannedYear?.toString(),
    governmentAuthDoc: formatFileList(governmentAuthDoc ? governmentAuthDoc.split(',') : []),
    thumbnail: formatFileList(thumbnail ? thumbnail.split(',') : []),
  };

  return formData;
};

// 数据回显 -- 格式处理 阶段1
const echoStageOneValue = (values: any) => {
  const {
    fsrView,
    eiaView,
    vfmView,
    faaView,
    plannedGovernmentSpendingView,
    riskAllocationFrameworkView,
    contractCoreContentView,
    indicatorsAndSystemView,
    contractSystemView,
    regulatoryFrameworkView,
    foreignInvestorsTaxPolicyView,
    foreignInvestorsExchangePolicyView,
    totalLandArea,
    totalLength,
    plannedTotalInvestment,
    projectContractTerm,
    plannedPriInvestmentAmount,
    plannedCompletionDate,
    plannedStartDate,
    plannedOperationStartDate,
    plannedProcurementDate,
    fsrApprovalDate,
    eiaApprovalDate,
    fsr,
    eia,
    riskAllocationFramework,
    contractCoreContent,
    indicatorsAndSystem,
    contractSystem,
    regulatoryFramework,
  } = values;

  const formData: any = {
    ...values,
    fsrView: !!fsrView,
    eiaView: !!eiaView,
    vfmView: !!vfmView,
    faaView: !!faaView,
    plannedGovernmentSpendingView: !!plannedGovernmentSpendingView,
    riskAllocationFrameworkView: !!riskAllocationFrameworkView,
    contractCoreContentView: !!contractCoreContentView,
    indicatorsAndSystemView: !!indicatorsAndSystemView,
    contractSystemView: !!contractSystemView,
    regulatoryFrameworkView: !!regulatoryFrameworkView,
    foreignInvestorsTaxPolicyView: !!foreignInvestorsTaxPolicyView,
    foreignInvestorsExchangePolicyView: !!foreignInvestorsExchangePolicyView,
    totalLandArea: totalLandArea?.toString(),
    totalLength: totalLength?.toString(),
    plannedTotalInvestment: plannedTotalInvestment?.toString(),
    projectContractTerm: projectContractTerm?.toString(),
    plannedPriInvestmentAmount: plannedPriInvestmentAmount?.toString(),
    plannedCompletionDate: plannedCompletionDate ? moment(plannedCompletionDate) : '',
    plannedStartDate: plannedStartDate ? moment(plannedStartDate) : '',
    plannedOperationStartDate: plannedOperationStartDate ? moment(plannedOperationStartDate) : '',
    plannedProcurementDate: plannedProcurementDate ? moment(plannedProcurementDate) : '',
    fsrApprovalDate: fsrApprovalDate ? moment(fsrApprovalDate) : '',
    eiaApprovalDate: eiaApprovalDate ? moment(eiaApprovalDate) : '',
    fsr: formatFileList(fsr ? fsr.split(',') : []),
    eia: formatFileList(eia ? eia.split(',') : []),
    riskAllocationFramework: formatFileList(riskAllocationFramework ? riskAllocationFramework.split(',') : []),
    contractCoreContent: formatFileList(contractCoreContent ? contractCoreContent.split(',') : []),
    indicatorsAndSystem: formatFileList(indicatorsAndSystem ? indicatorsAndSystem.split(',') : []),
    contractSystem: formatFileList(contractSystem ? contractSystem.split(',') : []),
    regulatoryFramework: formatFileList(regulatoryFramework ? regulatoryFramework.split(',') : []),
  };

  return formData;
};

// 数据回显 -- 格式处理  阶段2
const echoStageTwoValue = (values: any) => {
  const {
    // contractAgreedInvestmentAmount,
    contractBudgetExpenditure,
    privateAgreedInvestmentAmount,
    contractSigningDate,
    approvalDate,
    tenderSubmissionDeadline,
    finalNegotiationDate,
    preQualificationAnnouncement,
    preQualifiedShortlist,
    rfp,
    bidderList,
    bidsEvaluationResult,
    theSignedContract,
    contractCoreTerms,
  } = values;
  const formData: any = {
    ...values,
    // contractAgreedInvestmentAmount: contractAgreedInvestmentAmount?.toString(),
    contractBudgetExpenditure: contractBudgetExpenditure?.toString(),
    privateAgreedInvestmentAmount: privateAgreedInvestmentAmount?.toString(),
    contractSigningDate: contractSigningDate ? moment(contractSigningDate) : '',
    approvalDate: approvalDate ? moment(approvalDate) : '',
    tenderSubmissionDeadline: tenderSubmissionDeadline ? moment(tenderSubmissionDeadline) : '',
    finalNegotiationDate: finalNegotiationDate ? moment(finalNegotiationDate) : '',
    preQualificationAnnouncement: formatFileList(preQualificationAnnouncement ? preQualificationAnnouncement.split(',') : []),
    preQualifiedShortlist: formatFileList(preQualifiedShortlist ? preQualifiedShortlist.split(',') : []),
    rfp: formatFileList(rfp ? rfp.split(',') : []),
    bidderList: formatFileList(bidderList ? bidderList.split(',') : []),
    bidsEvaluationResult: formatFileList(bidsEvaluationResult ? bidsEvaluationResult.split(',') : []),
    theSignedContract: formatFileList(theSignedContract ? theSignedContract.split(',') : []),
    contractCoreTerms: formatFileList(contractCoreTerms ? contractCoreTerms.split(',') : []),
  };

  return formData;
};

// 数据回显 -- 格式处理  阶段3
const echoStageThreeValue = (values: any) => {
  const {
    pcRegisteredCapital,
    pcShareholdersPayProjectCapital,
    govExpenditureEachYear,
    pcFoundDate,
    constructionStartDate,
    constructionCompletionDate,
    operationStartDate,
    performanceAssuranceMeasures,
  } = values;
  const formData: any = {
    ...values,
    pcRegisteredCapital: pcRegisteredCapital?.toString(),
    pcShareholdersPayProjectCapital: pcShareholdersPayProjectCapital?.toString(),
    govExpenditureEachYear: govExpenditureEachYear?.toString(),
    pcFoundDate: pcFoundDate ? moment(pcFoundDate) : '',
    constructionStartDate: constructionStartDate ? moment(constructionStartDate) : '',
    constructionCompletionDate: constructionCompletionDate ? moment(constructionCompletionDate) : '',
    operationStartDate: operationStartDate ? moment(operationStartDate) : '',
    performanceAssuranceMeasures: formatFileList(performanceAssuranceMeasures ? performanceAssuranceMeasures.split(',') : []),
  };

  return formData;
};

// 数据回显 -- 格式处理  阶段4
const echoStageFourValue = (values: any) => {
  const {
    completionTime,
    warrantyPeriod,
    transferList,
    assessmentReport,
    performanceTestPlan,
    testResult,
    followUpOperation,
  } = values;
  const formData: any = {
    ...values,
    completionTime: completionTime ? moment(completionTime) : '',
    warrantyPeriod: warrantyPeriod?.toString(),
    transferList: formatFileList(transferList ? transferList.split(',') : []),
    assessmentReport: formatFileList(assessmentReport ? assessmentReport.split(',') : []),
    performanceTestPlan: formatFileList(performanceTestPlan ? performanceTestPlan.split(',') : []),
    testResult: formatFileList(testResult ? testResult.split(',') : []),
    followUpOperation: formatFileList(followUpOperation ? followUpOperation.split(',') : []),
  };

  return formData;
};

export { getUrlSearch,
  guid,
  genValidConfig,
  getStageOneInitialValue,
  handleStageOneValue,
  handleStageTwoValue,
  handleStageThreeValue,
  handleStageFourValue,
  handleFormValue,
  echoFormValue,
  echoStageOneValue,
  echoStageTwoValue,
  echoStageThreeValue,
  echoStageFourValue,
  deleteNullValue };
